import { mkdir, stat, readdir, copyFile } from 'fs/promises';
import path from 'path';

async function ensureDir(dir) {
  await mkdir(dir, { recursive: true });
}

async function walkAndCopy(srcDir, outDir, exts) {
  const entries = await readdir(srcDir, { withFileTypes: true });
  for (const entry of entries) {
    const srcPath = path.join(srcDir, entry.name);
    const destPath = path.join(outDir, entry.name);
    if (entry.isDirectory()) {
      await walkAndCopy(srcPath, destPath, exts);
    } else {
      const ext = path.extname(entry.name).toLowerCase();
      if (exts.includes(ext)) {
        await ensureDir(path.dirname(destPath));
        await copyFile(srcPath, destPath);
      }
    }
  }
}

async function main() {
  const [, , srcDirArg, outDirArg, ...extArgs] = process.argv;
  if (!srcDirArg || !outDirArg) {
    console.error('Usage: node copy-style-assets.mjs <srcDir> <outDir> [ext ...]');
    process.exit(1);
  }
  const srcDir = path.resolve(srcDirArg);
  const outDir = path.resolve(outDirArg);
  const exts = extArgs.length
    ? extArgs.map((ext) => (ext.startsWith('.') ? ext : `.${ext}`))
    : ['.css', '.less'];

  try {
    await stat(srcDir);
  } catch (error) {
    console.error(`Source directory not found: ${srcDir}`);
    process.exit(1);
  }

  await walkAndCopy(srcDir, outDir, exts);
}

main();
